package cn.luke.basic.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.luke.basic.debounces.Debounce;
import cn.luke.basic.entity.DtoUser;
import cn.luke.basic.log_api.LogApi;
import cn.luke.basic.rs.ResponseResult;
import cn.luke.basic.services.ServiceLogin;
import cn.luke.basic.utils.MyAssert;
import jakarta.annotation.Resource;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

/**
 * Created by Luke on 2025/3/7 16:58.
 */
@RestController
@ResponseResult
@SaCheckLogin
@RequestMapping("/auth")
public class ControllerAuth implements MyAssert {

    @Resource
    private ServiceLogin serviceLogin;

    /**
     * 登录
     * @param params 请求参数
     * @return DtoUser
     */
    @LogApi(value = "登录", excludeParams = {"password"})
    @Debounce
    @SaIgnore
    @PostMapping("/login")
    public DtoUser login(@RequestBody Map<String, Object> params) {
        String username = strIsNull(params.get("username"), "用户名不能为空");
        Assert.state(username.length()>=4, "用户名长度不能小于4, 请重新输入");
        String password = strIsNull(params.get("password"), "密码不能为空");
        Assert.state(password.length()>=6, "密码长度不能小于6, 请重新输入");
        Assert.state(password.length()<=25, "密码长度不能大于25, 请重新输入");
        return serviceLogin.doCheck(username, password);
    }

    /**
     * 判断是否登录
     * @return String
     */
    @RequestMapping("isLogin")
    public Boolean isLogin() {
        return StpUtil.isLogin();
    }

    /**
     * 用户登出
     */
    @LogApi("登出")
    @Debounce
    @PostMapping("/logout")
    public void logout() {
        if(StpUtil.isLogin()){
            StpUtil.getSession().logout();
            StpUtil.logout();
        }
    }

}
